package com.java.shiro;

import com.java.entity.PsFunction;
import com.java.entity.PsUser;
import com.java.service.PsFunctionService;
import com.java.service.PsUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author caiyuan
 * @version 1.0
 * @Date 2020/6/11 13:27 Dream-Seeker
 * @Description
 */
@Component("myShiroRealm")
public class MyShiorRealm extends AuthorizingRealm {

    @Autowired
    PsUserService psUserService;
    @Autowired
    PsFunctionService psFunctionService;

    //权限认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("！！！权限认证！！！");
        //获取全权限认证的主要身份【用户属性】
        String userName = (String) principals.getPrimaryPrincipal();
        System.out.println("需要进行权限认证的用户：" + userName);
        //获取当前登录用户拥有的角色列表
        //根据用户姓名获取角色信息
        PsUser user = psUserService.getUserbyName(userName);
        System.out.println("权限验证用户的角色：" + user.getRole().getRoleName());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        List<PsFunction> premissions = psFunctionService.getPerbyRoleId(user.getRole().getId());
        System.out.println(premissions);
        for (PsFunction premission : premissions) {
            info.addStringPermission(premission.getId()+"");
        }
        return info;
    }

    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("!!!用户身份认证!!!");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String userName = usernamePasswordToken.getUsername();
        String password = String.valueOf(usernamePasswordToken.getPassword());
        System.out.println("当前登录的用户：" + userName);

        //去数据库查询当前用户
        PsUser user = psUserService.login(userName, password);
        if (user == null) {
            System.out.println("没有查询到该用户");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName, user.getUserPassword(), getName());
        return info;
    }
}
